
<template>
  <audio ref="audio" src='/ocean.mp3' controls loop></audio>
  <canvas id="canvas" ref="canvasMedia"></canvas>
</template>
    
<script  setup>
import { onMounted, getCurrentInstance } from 'vue';
import themecolor from "@/assets/index.module.scss";


const pageInstance = getCurrentInstance();
let canvas = '', canvasCtx = '';
let bufferLength = '', audioAnalyser = '';
let dataArray = [];


onMounted(() => {
  canvas = pageInstance.refs.canvasMedia;
  canvasCtx = canvas.getContext('2d')
  audioContext();

  console.log('themeColor.....audio......>', themecolor);
  console.log('themeColor.....audio...dddd...>', themecolor.themecolor);


})

function audioContext() {
  let audio = pageInstance.refs.audio;

  audio.onplay = () => {
    console.log('play..........');
    let audioCtx = new AudioContext();

    let audioSource = audioCtx.createMediaElementSource(audio);

    //创建一个AnalyserNode，用于公开音频事件和频率数据，例如创建数据可视化；
    audioAnalyser = audioCtx.createAnalyser();
    audioSource.connect(audioAnalyser);
    audioAnalyser.connect(audioCtx.destination);
    audioAnalyser.fftSize = 1024;
    bufferLength = audioAnalyser.frequencyBinCount;
    dataArray = new Uint8Array(bufferLength);


    //用于控制音频图形的整体音量,控制音量变大变小；
    let audioGain = audioCtx.createGain();
    // console.log('audioGain...>', audioGain);
    //用于控制音频图形的周期波形；
    // let audioWave = audioCtx.createPeriodicWave();
    draw()
  }
}


function draw() {
  requestAnimationFrame(draw);
  let { width, height } = canvas
  canvasCtx.clearRect(0, 0, width, height);

  audioAnalyser.getByteFrequencyData(dataArray);
  canvasCtx.fillStyle = '#fff';
  canvasCtx.fillRect(0, 0, width, height);

  for (let index = 0; index < bufferLength; index++) {
    const barHeight = dataArray[index];
    var barWidth = (width / bufferLength) * 3;
    // canvasCtx.fillStyle = themehcolor.themehcolor;//'#67C23A';

    canvasCtx.fillStyle = '#67C23A';
    canvasCtx.fillRect(index * barWidth + 20, height - barHeight / 2, barWidth, barHeight);
  }
}
</script>   
<style scoped lang="scss">
audio {
  position: absolute;
  opacity: 0.3;
  z-index: 99;
  background-color: var(--backgroundColor);
}

canvas {
  width: 100%;
  height: 99%;
}

audio:hover {
  opacity: 0.5;
}
</style>